const { classesModel } = require('../models/classesModel');
const { studentsModel } = require('../models/studentsModel');
//新增班级
module.exports.createClasses = async function(req, res) {
    const data = req.body;
    await classesModel.create(data);
    res.send({
        message: '新增班级成功',
        code: 1
    })
}
module.exports.getClasses = async function(req, res) {

    const result = await classesModel.find().populate('majorId');
    // console.log(result);
    res.send({
        message: '获取班级数据班级成功',
        code: 1,
        result
    })
}

//删除班级
module.exports.delClasses = async function(req, res) {
    const data = req.body;
    const result = await studentsModel.find({ classesId: data._id });
    // console.log(result);
    if (result.length > 0) {
        res.send({
            message: '删除失败，该班级有学生',
            code: 0,
        })
    } else {

        await classesModel.deleteOne(data);
        res.send({
            message: '删除成功',
            code: 1,
        })
    }
}

//修改班级
module.exports.subGetClasses = async function(req, res) {
    const data = req.body;
    const result = await classesModel.find(data).populate('majorId');
    res.send({
        message: '获取班级数据成功',
        code: 1,
        result
    })
}
module.exports.changeClasses = async function(req, res) {
    const { _id, name } = req.body;
    const result = await classesModel.find({ name });
    if (result.length > 0) {
        res.send({
            message: '班级已存在',
            code: 0,
        })
    } else {
        await classesModel.updateOne({ _id }, { name });
        res.send({
            message: '修改成功',
            code: 1

        })
    }
}